package io.github.mayubao.resume.faq;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Process;
import android.util.Log;

import java.util.List;

/**
 * Created by Administrator on 2018/3/24.
 */

public class AppContext extends Application {

    private static final String TAG = AppContext.class.getSimpleName();

    private static AppContext mAppContext;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "AppContext--->>>onCreate");
        Log.i(TAG, "此进程的名称--->>>" + getProcessName(this, android.os.Process.myPid()));

        /**
         * 下面实现如何过滤子进程，避免多次初始化Application
         */
        if(!isMainProcess()){ //非主进程的话直接返回
            return;
        }

        Log.i(TAG, "主进程--->>>初始化工作开始...");
        mAppContext = this;
    }

    /**
     * 判断是否为主进程
     * @return
     */
    public boolean isMainProcess(){
        return getPackageName().equals(getProcessName(this, android.os.Process.myPid()));

    }


    /**
     * 获取进程名称
     * @param cxt
     * @param pid
     * @return
     */
    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

    /**
     * 获取AppContext上下文
     * @return
     */
    public static AppContext getAppContext(){
        return mAppContext;
    }
}
